<?php

namespace app\data\controller\control;
use app\data\model\ControlClaimModel;
use app\data\model\ControlPlanListModel;
use app\data\model\ControlPlanModel;
use app\data\model\StorehouseDataModel;
use think\admin\Controller;
use think\admin\extend\CodeExtend;
use think\facade\Db;

/**
 * 出库管理
 * Class Cate
 * @package app\data\controller\shop
 */
class ExWarehouse extends Controller
{
    /**
     * 指定数据表
     * @var string
     */
    protected $table = 'SnControlPlan';

    /**
     * 出库管理
     * @auth true
     * @menu true
     */
    public function index()
    {
        $this->title = "出库管理";
        // 加载对应数据
        $query = $this->_query($this->table);
        $query->order('id desc')->page();
    }


    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _index_page_filter(array &$data)
    {

    }

     /**
     * 出库提交
     * @auth true
     * @menu true
     */
    public function addPlanCollect(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('材料员不存在');}
        if(!isset($data['plan_list']) || empty($data['plan_list'])){$this->error('数据不可为空');}
        $plan_list = json_decode($data['plan_list'],true);
        foreach ($plan_list as $ks => $vs){
            if(!$vs['material_num'] || empty($vs['material_num'])){$this->error($vs['material_name'].'('.$vs['material_code'].')'.'数量不可为0');}
        }
        $userInfo = Db::name('system_user')->where('id',$data['admin_id'])->where('is_deleted',0)->field('id,nickname,username')->find();
        if(!$userInfo){$this->error('材料员不存在');}
        //开启事务
        Db::startTrans();
        try{
            //获取标题
            $data['plan_data_status'] = date('Ym',time());
            $data['plan_title'] = date('Y年m月d日',time()).'领用单（扫码）';
            $data['status'] = 1;
            $data['plan_type'] = 2;
            $data['admin_id'] = $userInfo['id'];
            $data['admin_name'] = $userInfo['username'];
            // 生成领用ID
            $data['id'] = CodeExtend::uniqidNumber(10,'L');
            //获取剩余物资
            $adminStorehouse = Db::name('sn_enter_storehouse_'.$data['admin_id'])->column('material_num','material_code');
            //数组合并array_combine($k,$v)  return $k=>$v
            $combineData= array_combine(array_column($plan_list,'material_code'),array_column($plan_list,'ex_num'));
            foreach ($combineData as $key=>$val){
                $he = $adminStorehouse[$key] - $val;
                if($he < 0 ){throw new \Exception($key.'数量不足');}
                // 减自己库存
                $res = Db::name('sn_enter_storehouse_'.$data['admin_id'])->where('material_code',$key)->dec('material_num',$val)->update();
                if (!$res) {throw new \Exception("服务器错误");}
            }
            $cate_list = array();
            //组合数组
            foreach ($plan_list as $k=>$v){
                $cate_list[$k]['material_code'] = $v['material_code'];
                $cate_list[$k]['material_name'] = $v['material_name'];
                $cate_list[$k]['material_model'] = $v['material_model'];
                $cate_list[$k]['material_unit'] = $v['material_unit'];
                $cate_list[$k]['material_price'] = $v['material_price'];
                $cate_list[$k]['material_num'] = $v['ex_num'];
                $cate_list[$k]['material_xjprice'] = sprintf("%01.2f", $v['ex_num'] * $v['material_price']);
                $cate_list[$k]['plan_id'] = $data['id'];
                $cate_list[$k]['plan_time'] = date('Y-m-d H:i:s',time());
                // $cate_list[$k]['cate_id'] = $v['cate_id'];
                $cate_list[$k]['admin_id'] = $userInfo['id'];
                $cate_list[$k]['admin_name'] = $userInfo['username'];
                $cate_list[$k]['status'] = 1;
            }
            // 子表数据添加
            $applyAll = Db::name('sn_control_claim_list')->insertAll($cate_list);
            if (!$applyAll) {throw new \Exception("服务器错误");}
            $data['plan_list'] = json_encode($cate_list,true);
            //主表数据添加
            $planSave = ControlClaimModel::insertGetId($data);
            if (!$planSave) {throw new \Exception("服务器错误");}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());die;
        }
        $this->success('数据更新成功');
    }


}